layui.use(['layer','laypage','form','util','laydate'],function(){
		var layer = layui.layer,
		laypage = layui.laypage,
		form = layui.form,
		laydate = layui.laydate,
		util = layui.util,
		$ = layui.$;
		
	var limit = 3;
    var counts = 0;
    
    var nums = 0;
    
    var cids = ",";
    var cnums = ',';
    var cprices = ",";
    var gids = ",";
    var gcids = ",";
    var gsids = ",";
    var geids = ",";
	
	if($("#uid").val()!=""){
		//初始化
		loadCar(1);
		showPage();
		loadAddress();
	}
	
	//显示分页
	function showPage(){
	  laypage.render({
	    elem: 'pageLimit'	//分页标签显示的位置
		,count:counts	//总的记录条数
		,limit:limit	//每一页的数据条数
	    ,layout: ['count', 'prev', 'page', 'next', 'limit', 'refresh', 'skip']	//在页面中显示的样式
	  	,jump: function(obj, first){
	      if(!first){
	    	  loadCar(obj.curr);
	      }
	    }
	  });
	}
	
	//加载地址
	function loadAddress(){
		var jsonAddress = {};
		jsonAddress['user.uid'] = $("#uid").val();
		$.ajax({
			type:"post",
			url:"address/findManyByPramas",
			data:jsonAddress,
			success:function(data){
				var html = '';
				$.each(data,function(i,item){
					if(item.atype==1){
						html += '<option value="'+item.aid+'" selected="selected">'+item.loc+'</option>';
					}else{
						html += '<option value="'+item.aid+'">'+item.loc+'</option>';
					}
				});
				$("#aid").html(html);
			},
			error:function(){
				layer.msg("对不起，服务器异常！！！",{"icon":3,"time":2000});
			}
		});
	};
	
	//获取计时器(倒计时)
	function getEndDate(endCarDate,cid,cnum){
		var time = endCarDate.split(",");
		//调用显示倒计时的方法
		setCountdown(time[0],time[1]-1,time[2],time[3],time[4],time[5],cid,cnum);
	}
	//倒计时
	function setCountdown(y, M, d, H, m, s,cid,cnum){
	    var endTime = new Date(y, M||0, d||1, H||0, m||0, s||0) //结束日期
	    ,serverTime = new Date(); //假设为当前服务器时间，这里采用的是本地时间，实际使用一般是取服务端的
	    
	    util.countdown(endTime, serverTime, function(date, serverTime, timer){
	      var str = date[0] + '天' + date[1] + '时' +  date[2] + '分' + date[3] + '秒';
	      $('#date'+cid).html('还剩：'+str);
	      if($('#date'+cid).text()=="还剩：0天0时0分0秒"){
	    	  $('#delete'+cid).html('<img style="width: 35px;height: 35px;" src="/zzbinGood/delete.jpg"/>');
	    	  $('#date'+cid).html('<span style="color: #613030;margin-left: 80px;">已失效</span>');
	    	  $('#checkedDiv'+cid).html('<span>'+cnum+'</span>');
	      }
	    });
	    return false;
	};
	
	//加载购物车数据
	function loadCar(page){
  	  	var jsonCar = {};
  	  	jsonCar['user.uid'] = $("#uid").val();
		$.ajax({
			url: "car/listByPramas?page="+page+"&limit="+limit,
			type: 'post',
			data: jsonCar,
			async: false,
			success:function(res){
				//循环数据集合，通过jquery的append()方法将标签加入到ul中
				var carHtml='';
				$('.carTable').html('');	//清空
				$.each(res.data,function(index,car){
					carHtml += '<tr class="cart_item" id="tr'+car.cid+'">';

					if(car.endCarDate>new Date()){
						carHtml += '<td class="product-price"><span id="delete'+car.cid+'"><input class="form-control sm" type="checkbox" id="checkboxCar" value="'+car.cid+','+car.cnum+','+car.cprice+','+car.good.gid+','+car.goodColor.gcid+','+car.goodSize.gsid+','+(car.good.price*car.good.discount).toFixed(2)+'"/></span></td>';
					}else{
						carHtml += '<td class="product-price"><a id="carDelete"><img style="width: 35px;height: 35px;" src="/zzbinGood/delete.jpg"/><a></td>';
					}
					
		            carHtml += '<td class="product-desc">';
		            carHtml += '<dl>';
		            carHtml += '<dt class="hidden-xs"><a href="good/goodDetails?gid='+car.good.gid+'"><img style="width: 130px;height: 120px;" src="/zzbinGood/'+car.good.gpicpath+'" alt=""></a></dt>';
		            carHtml += '<dd>';
		            carHtml += '<span style="color: #FD638F;">生成时间：'+car.makeCarDate+'</span>';

					if(car.endCarDate>new Date()){
						carHtml += '<span id="date'+car.cid+'" style="color: #01814A;margin-left: 80px;"></span>';
						getEndDate(formatDateTime(car.endCarDate),car.cid,car.cnum);
					}else{
						carHtml += '<span style="color: #613030;margin-left: 80px;">已失效</span>';
					}
					
		            carHtml += '<h3>'+car.good.gname+'</h3>';
		            carHtml += '<p class="hidden-xs">'+car.good.goodType.tname+'/'+car.good.goodType.tdesc+'/'+car.good.gdesc+'</p>';
		            carHtml += '</dd>';
		            carHtml += '</dl>';
		            carHtml += '</td>';
		            carHtml += '<td class="product-price">';
		            carHtml += '<h3>'+car.goodSize.gsname+'</h3>';
		            carHtml += '</td>';
		            carHtml += '<td class="product-price">'+car.goodColor.gcname+'</td>';
		            carHtml += '<td class="product-price">$'+(car.good.price*car.good.discount).toFixed(2)+'</td>';
		            carHtml += '<td class="product-price">';
		            if(car.endCarDate>new Date()){
			            carHtml += '<div class="quantity buttons_added" id="checkedDiv'+car.cid+'">';
			            carHtml += '<button class="minus" value="'+car.good.gid+','+car.goodColor.gcid+','+car.goodSize.gsid+','+(car.good.price*car.good.discount).toFixed(2)+','+car.cid+'"><i class="fa fa-minus"></i></button>';
			            carHtml += '<input type="text" size="3" class="qty text form-control" value="'+car.cnum+'" name="qty" id="numsInp'+car.cid+'" step="1" onkeypress="return (/[\d]/.test(String.fromCharCode(event.keyCode)))">';
			            carHtml += '<button class="plus" value="'+car.good.gid+','+car.goodColor.gcid+','+car.goodSize.gsid+','+(car.good.price*car.good.discount).toFixed(2)+','+car.cid+'"><i class="fa fa-plus"></i></button>';
			            carHtml += '</div>';
					}else{
						carHtml += '<span>'+car.cnum+'</span>';
					}
		            carHtml += '</td>';
		            carHtml += '<td class="product-price">';
		            carHtml += '<h3>$<span id="carPrice'+car.cid+'">'+car.cprice+'</span></h3>';
		            carHtml += '</td>';
		            carHtml += '</tr>';
				});
				$('.carTable').html(carHtml);
				//将总的记录条数赋值给counts
				counts = res.count;
			},
			error:function(){
				layer.msg("服务器异常！！！",{"icon":3,"time":2000});
			}
		});
	}
	
	//加载商品数量(库存)
	function loadGoodNum(jsonGoodNum){
		$.ajax({
			type:"post",
			url:"goodnum/findSum",
			async:false,
			data:jsonGoodNum,
			success:function(data){
				if(data===''){
					data = 0;
				}
				nums = data;
			},error:function(){
				swal("服务器异常!","","warning",{buttons: {}});
			}
		}); 
	}

	//点击增加商品
	$(".plus").click(function(){
		var i = 0.0;
		var pluss = this.value.split(",");
		var checknums = $("#numsInp"+pluss[4]).val();
		//console.log(this.value);
		var jsonGoodNum = {};
		jsonGoodNum['gid'] = pluss[0];
		jsonGoodNum['gcid'] = pluss[1];
		jsonGoodNum['gsid'] = pluss[2];
		//console.log(jsonGoodNum);
		loadGoodNum(jsonGoodNum);
		if(nums>0){
			if(checknums<5){
				checknums++;
				nums--;
				i = i + 1.0;
				jsonGoodNum['gnum'] = nums;
				//console.log(nums);
				updGoodNum(jsonGoodNum)
				jsonGoodNum['cid'] = pluss[4];
				jsonGoodNum['cnum'] = checknums;
				jsonGoodNum['cprice'] = (pluss[3]*checknums).toFixed(2);
				jsonGoodNum['makeCarDate'] = new Date();
				updCar(jsonGoodNum)
				$("#numsInp"+pluss[4]).val(checknums);
				$('#carPrice'+pluss[4]).text((pluss[3]*checknums).toFixed(2));
				if(cids!=','){
					$(".caramount").text((parseFloat($(".caramount").text())+parseFloat(pluss[3]*i)).toFixed(2));
				}
			}else{
				layer.msg("最多选择五件！",{"icon":5,"time":2000});
			}
		}else{
			layer.msg("已经是最大了！",{"icon":5,"time":2000});
		}
	});

	//点击减少商品
	$(".minus").click(function(){
		var i = 0.0;
		var minuss = this.value.split(",");
		var checknums = $("#numsInp"+minuss[4]).val();
		//console.log(this.value);
		var jsonGoodNum = {};
		jsonGoodNum['gid'] = minuss[0];
		jsonGoodNum['gcid'] = minuss[1];
		jsonGoodNum['gsid'] = minuss[2];
		//console.log(jsonGoodNum);
		loadGoodNum(jsonGoodNum);
		if(checknums>1){
			checknums--;
			nums++;
			i++;
			jsonGoodNum['gnum'] = nums;
			//修改库存
			updGoodNum(jsonGoodNum);
			//修改购物车数量
			jsonGoodNum['cid'] = minuss[4];
			jsonGoodNum['cnum'] = checknums;
			jsonGoodNum['cprice'] = (minuss[3]*checknums).toFixed(2);
			jsonGoodNum['makeCarDate'] = new Date();
			updCar(jsonGoodNum)
			$("#numsInp"+minuss[4]).val(checknums);
			$('#carPrice'+minuss[4]).text((minuss[3]*checknums).toFixed(2));
			if(cids!=','){
				$(".caramount").text((parseFloat($(".caramount").text())-parseFloat(minuss[3]*i)).toFixed(2));
			}
		}else{
			layer.msg("已经是最小了！",{"icon":5,"time":2000});
		}
	});
	
	//修改购物车数量
	function updCar(jsonGoodNum){
		$.ajax({
			url:'car/updT',
			type:"post",
			data:jsonGoodNum,
			success:function(res){
				
			},
			error:function(){
				swal("对不起,服务器异常!"," ","warning",{buttons: {}});
			} 
		});
	}
	
	//修改商品数量(库存)
	function updGoodNum(jsonGoodNum){
		$.ajax({
			type:"post",
			url:"goodnum/updT",
			async:false,
			data:jsonGoodNum,
			success:function(data){
				
			},error:function(){
				swal("服务器异常!","","warning",{buttons: {}});
			}
		}); 
	}
	
	$(".carTable").on("click","#checkboxCar",function(){
		if($(this).is(":checked")){
			var arrcheck = $(this).val().split(",");
			cids += arrcheck[0]+",";
			cnums += $("#numsInp"+arrcheck[0]).val()+",";
			cprices += $('#carPrice'+arrcheck[0]).text()+",";
			gids += arrcheck[3]+",";
			gcids += arrcheck[4]+",";
			gsids += arrcheck[5]+",";
			geids += 0+",";
			$(".caramount").text((parseFloat($(".caramount").text())+parseFloat($('#carPrice'+arrcheck[0]).text())).toFixed(2));
			$("#checkedDiv"+arrcheck[0]).html('<span id="numsSpan'+arrcheck[0]+'">'+$("#numsInp"+arrcheck[0]).val()+'</span>');
		}else{
			var arrcheck = $(this).val().split(",");
			cids = cids.replace(","+arrcheck[0]+",",",");
			cnums = cnums.replace(","+$("#numsInp"+arrcheck[0]).val()+",",",");
			cprices = cprices.replace(","+$('#carPrice'+arrcheck[0]).text()+",",",");
			gids = gids.replace(","+arrcheck[3]+",",",");
			gcids = gcids.replace(","+arrcheck[4]+",",",");
			gsids = gsids.replace(","+arrcheck[5]+",",",");
			geids = geids.replace(","+0+",",",");
			$(".caramount").text((parseFloat($(".caramount").text())-parseFloat($('#carPrice'+arrcheck[0]).text())).toFixed(2));
			$("#checkedDiv"+arrcheck[0]).html('<button class="minus" value="'+arrcheck[3]+','+arrcheck[4]+','+arrcheck[5]+','+arrcheck[6]+','+arrcheck[0]+'"><i class="fa fa-minus"></i></button><input type="text" size="3" class="qty text form-control" value="'+$("#numsSpan"+arrcheck[0]).text()+'" name="qty" id="numsInp'+arrcheck[0]+'" step="1" onkeypress="return (/[\d]/.test(String.fromCharCode(event.keyCode)))"><button class="plus" value="'+arrcheck[3]+','+arrcheck[4]+','+arrcheck[5]+','+arrcheck[6]+','+arrcheck[0]+'"><i class="fa fa-plus"></i></button>');
		}
	});
	
	//提交订单
	$("#saveOrders").click(function(){
		if(cids!=','){
			var jsonOrders = {};
			jsonOrders['oname'] = getnewdata(new Date())+randomNum(6);
			jsonOrders['makeOrderDate'] = new Date();
			jsonOrders['gids'] = gids.substring(1,gids.length-1);
			jsonOrders['cnums'] = cnums.substring(1,cnums.length-1);
			jsonOrders['cprices'] = cprices.substring(1,cprices.length-1);
			jsonOrders['oprice'] = $(".caramount").text();
			jsonOrders['state'] = 1;
			jsonOrders['user.uid'] = $("#uid").val();
			jsonOrders['address.aid'] = $("#aid").val();
			jsonOrders['gcids'] = gcids.substring(1,gcids.length-1);
			jsonOrders['gsids'] = gsids.substring(1,gsids.length-1);
			jsonOrders['geids'] = geids.substring(1,geids.length-1);
			//console.log(jsonOrders);
			//添加
			saveOrders(jsonOrders);
		}else{
			layer.msg("您还未选择商品！",{"icon":5,"time":2000});
		}
		
	});
	
	//添加
	function saveOrders(jsonOrders){
	
		$.ajax({
			type:"post",
			url:"orders/saveT",
			data:jsonOrders,
			success:function(data){
				if(data=="success"){
					layer.msg("订单提交成功。。",{"icon":6,"time":2000});
					//删除
					var params = "";
					params = cids.substring(1,cids.length-1);
					var s = params.split(",");
					for(var i=0;i<s.length;i++){
						$("#tr"+s[i]).hide();
					}
				    cids = ",";
				    cnums = ',';
				    cprices = ",";
				    gids = ",";
				    gcids = ",";
				    gsids = ",";
				    geids = ",";
					deleteOrders(params)
				}else{
					layer.msg("订单提交失败！！",{"icon":2,"time":2000});
				}
			},
			error:function(){
				layer.msg("对不起，服务器异常！！！",{"icon":3,"time":2000});
			}
		});
	}
	
	//删除
	function deleteOrders(params){
		console.log(params);
		$.ajax({
			type:"post",
			url:"car/deletes",
			data:{params:params},
			success:function(data){
				if(data=="success"){
					layer.msg("订单删除成功。。",{"icon":6,"time":2000});
				}else{
					layer.msg("订单删除失败！！",{"icon":2,"time":2000});
				}
			},
			error:function(){
				layer.msg("对不起，服务器异常！！！",{"icon":3,"time":2000});
			}
		});
	}
	
	$("#saveAddress").click(function(){
		layer.open({
			  type: 1,
			  title: '添加地址',
			  offset: 'cb',	//弹出框弹出的坐标位置（cb:中间）
			  content: $("#saveAddressDiv"),
			  area: ['510px','520px'],
		  	  btn: '提交',
		  	  btnAlign: 'cb',	//按钮右下角
		  	  shade: 0,	//不显示遮罩
		  	  yes: function(index){		//bnt按钮的点击事件
		  		  var reg = /^1[3|5|8]{1}[0-9]{9}$/;
		  		  if($("#loc").val()!=""){
		  			  if($("#aname").val()!=""){
		  				  if($("#iphone").val()!=""){
		  					  if(reg.test($("#iphone").val())){
			  			  		  var jsonAddress = {};
			  			  		  jsonAddress['loc'] = $("#province4").val()+$("#city4").val()+$("#district4").val()+$("#loc").val();
			  			  		  jsonAddress['aname'] = $("#aname").val();
			  			  		  jsonAddress['iphone'] = $("#iphone").val();
			  			  		  jsonAddress['atype'] = $('#atype input[name="atype"]:checked ').val();
			  			  		  jsonAddress['user.uid'] = $("#uid").val();
			  			  		  //console.log(jsonAddress);
			  			  		  if($('#atype input[name="atype"]:checked ').val()==1){
			  			  			  saveOrUpdateAddress(jsonAddress,"address/updT","地址修改");
			  			  			  saveOrUpdateAddress(jsonAddress,"address/saveT","地址添加");
			  			  			  loadAddress();
				  			  		  layer.close(index);
			  			  		  }else{
			  			  			  saveOrUpdateAddress(jsonAddress,"address/saveT","地址添加");
			  			  			  loadAddress();
				  			  		  layer.close(index);
			  			  		  }
		  					  }else{
					  			  layer.msg("请输入正确的手机号！",{"icon":2,"time":2000});
					  		  }
		  				  }else{
				  			  layer.msg("未输入手机号！",{"icon":2,"time":2000});
				  		  }
		  			  }else{
			  			  layer.msg("未输入收货人！",{"icon":2,"time":2000});
			  		  }
		  		  }else{
		  			  layer.msg("未输入详细地址！",{"icon":2,"time":2000});
		  		  }
		  	  }
		 });
	});
	
	//添加地址
	function saveOrUpdateAddress(jsonAddress,url,msg){
		$.ajax({
			type:"post",
			url:url,
			data:jsonAddress,
			success:function(data){
				if(data=="success"){
					layer.msg(msg+"成功。",{"icon":6,"time":2000});
				}else{
					layer.msg(msg+"失败！",{"icon":2,"time":2000});
				}
			},
			error:function(){
				layer.msg("对不起，服务器异常！",{"icon":3,"time":2000});
			}
		});
	}
	
	//转换字符串的方法
	function getDnoData(arr){
		var str = "";
		for (var i = 0; i < arr.length; i++) {
			if(arr[i]!=""){
				if(str==""){
					str = arr[i];
				}else{
					str += "," + arr[i];
				}
			}
		}
		return str;
	}

	//生成位的随机数
	function randomNum(n){ 
	  var t=''; 
	  for(var i=0;i<n;i++){ 
		  t+=Math.floor(Math.random()*10); 
	  } 
	  return t; 
	}
	
	//格式化时间
	function getnewdata(d){
	    var curr_date = d.getDate();
	    var curr_month = d.getMonth() + 1; 
	    var curr_year = d.getFullYear();
	    String(curr_month).length < 2 ? (curr_month = "0" + curr_month): curr_month;
	    String(curr_date).length < 2 ? (curr_date = "0" + curr_date): curr_date;
	    var yyyyMMdd = curr_year + "" + curr_month +""+ curr_date;
	    return yyyyMMdd;
	}

	//将时间戳转换为yyyy-MM-dd HH:mm:ss
	function formatDateTime(inputTime) {  
	    var date = new Date(inputTime);
	    var y = date.getFullYear();
	    var m = date.getMonth() + 1;
	    m = m < 10 ? ('0' + m) : m;
	    var d = date.getDate();
	    d = d < 10 ? ('0' + d) : d;
	    var h = date.getHours();
	    h = h < 10 ? ('0' + h) : h;
	    var minute = date.getMinutes();
	    var second = date.getSeconds();
	    minute = minute < 10 ? ('0' + minute) : minute;  
	    second = second < 10 ? ('0' + second) : second; 
	    return y + ',' + m + ',' + d+','+h+','+minute+','+second;
	};
	
	//将时间戳转换为yyyy-MM-dd HH:mm:ss
	function getDateTime(inputTime) {  
	    var date = new Date(inputTime);
	    var y = date.getFullYear();
	    var m = date.getMonth() + 1;
	    m = m < 10 ? ('0' + m) : m;
	    var d = date.getDate();
	    d = d < 10 ? ('0' + d) : d;
	    var h = date.getHours();
	    h = h < 10 ? ('0' + h) : h;
	    var minute = date.getMinutes();
	    var second = date.getSeconds();
	    minute = minute < 10 ? ('0' + minute) : minute;  
	    second = second < 10 ? ('0' + second) : second; 
	    return y + '/' + m + '/' + d+' '+h+':'+minute+':'+second;
	};
	
});